package com.booter.ws.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * 无法获取header中的值，只能获取url中的参数，如果token用jwt等很长的，用这种方式实现并不友好
 */
@Component
@Slf4j
public class RouteWebSocketInterceptor extends HttpSessionHandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse seHttpResponse,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
//        try {
//            String token = serverHttpRequest.getHeaders().getFirst("Authorization");
//            String userId = StringUtils.isNotBlank(token) ? JwtUtil.getClaim(token, Constants.ACCOUNT) : "";
//            log.info("account:{}", userId);
//            if (StringUtils.isNotBlank(userId)) {
//                serverHttpRequest.getHeaders().set(WsConstant.ACCOUNT_HEADER_NAME, userId);
//            } else {
//                seHttpResponse.setStatusCode(HttpStatus.FORBIDDEN);
//                return false;
//            }
//        } catch (Exception ex) {
//            log.error("WS异常", ex);
//            return false;
//        }

//        seHttpResponse.getHeaders().set("Access-Control-Allow-Credentials", "true");
//        seHttpResponse.getHeaders().set("Access-Control-Allow-Headers", "*");
//        seHttpResponse.getHeaders().set("Access-Control-Allow-Origin", "*");

        return super.beforeHandshake(serverHttpRequest, seHttpResponse, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
//        response.getHeaders().set("Access-Control-Allow-Credentials", "true");
//        response.getHeaders().set("Access-Control-Allow-Headers", "*");
//        response.getHeaders().set("Access-Control-Allow-Origin", "*");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}